const Koa = require('koa');
const Router = require('koa2-router')
const static = require('koa-static')
const path = require('path');
const env = require('./env')
const views = require('koa-views');
const app = new Koa();
const router = new Router();
const addon = require('../addon/build/Release/addon')
 
//global exception handler
const catchError = async (ctx,next)=>{
    try{
        await next()
    } catch(error){
        if(error.status != 404)
             console.log(error)
        throw error;
    }
}
app.use(catchError)

//static file 
app.use(static(path.join(__dirname,'/static/'),{}));

//template
app.use(views(path.join(__dirname, './views'), {
    extension: 'ejs'
}))

router.get('/',async (ctx, next) =>{
    await ctx.render('showImage', { title: 'show image' });
})


router.get('/image',async (ctx, next) =>{
  const fileMap = new addon.FileMap();
  var buf = fileMap.open(env.file_mapping_name, env.image_height*env.image_width,0);
  if(!buf)
  {
        console.log('file mapping is not opened');
        ctx.throw(500);
  }

  ctx.set("Content-Type", "application/octet-stream");
  ctx.response.body = buf;
})


app.use(router);

app.use(ctx => {
    console.log(`Not Found:${ctx.URL}`);
    ctx.throw(404);
});

const port = env.port;
app.listen(port,() => {
    console.log(`web app started, listening at ${port}`);
});
